package com.pandy.seckill.service.impl;

import com.pandy.leopard.util.SnowFlakeUtil;
import com.pandy.seckill.mapper.SeckillSegmentStockMapper;
import com.pandy.seckill.model.SeckillSegmentStock;
import com.pandy.seckill.model.SeckillSku;
import com.pandy.seckill.mapper.SeckillSkuMapper;
import com.pandy.seckill.respose.AddSeckillSkuRespose;
import com.pandy.seckill.service.ISeckillSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pandy.seckill.vo.SeckillSkuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 秒杀商品表 服务实现类
 * </p>
 *
 * @author pandy
 * @since 2025-04-08
 */
@Service
public class SeckillSkuServiceImpl extends ServiceImpl<SeckillSkuMapper, SeckillSku> implements ISeckillSkuService {

    @Autowired
    private SeckillSegmentStockMapper seckillSegmentStockMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public SeckillSkuVO addSeckillSku(AddSeckillSkuRespose respose) {
        SeckillSku seckillSku = new SeckillSku();
        BeanUtils.copyProperties(respose, seckillSku);

        // 设置ID
        seckillSku.setId(SnowFlakeUtil.getDefaultSnowFlakeId());

        // 设置库存
        seckillSku.setRawStockCount(respose.getStockCount());
        seckillSku.setStockCount(respose.getStockCount());

        this.baseMapper.insert(seckillSku);

        // 插入库存表
        SeckillSegmentStock stock = new SeckillSegmentStock();
        stock.setId(SnowFlakeUtil.getDefaultSnowFlakeId());
        stock.setSkuId(seckillSku.getId());
        stock.setStockCount(seckillSku.getStockCount());
        stock.setRawStockCount(seckillSku.getRawStockCount());
        seckillSegmentStockMapper.insert(stock);

        SeckillSkuVO vo = new SeckillSkuVO();
        BeanUtils.copyProperties(seckillSku, vo);
        return vo;
    }
}
